<script setup lang="ts">
import { getTransferSearch } from "@/api/stock/transfer";
import { ImageViewer } from "@/components/common/ImageViewer";
import { message } from "@/utils/message";
import Delete from "@iconify-icons/ep/delete";
import EpSelect from "@iconify-icons/ep/select";
import { computed, ref, watch } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
import { useColumns } from "./columns";
const { kcpdColumns } = useColumns();

const props = withDefaults(defineProps<FormProps>(), {
  selectData: {}
});

const tableList = ref([]);
const ruleFormRef = ref();
const newForm = ref<any>({
  depositoryType: 1,
  goodsList: []
});

const showCkList = computed(() => {
  // 仓库类型 0门店仓 1供应链总仓 2区域仓
  let filterType = newForm.value.depositoryType == 1 ? [1, 2] : [0];
  return props.selectData.ckList.filter(v => filterType.includes(v.type));
});

const depositoryChange = () => {
  remoteMethod("");
};

const chooseGoodsVal = ref([]);
const searchLoading = ref(false);
const searchGoodsList = ref([]);
const remoteMethod = async (searchKey: string) => {
  if (searchLoading.value) {
    return;
  }
  searchLoading.value = true;
  let depositoryType = newForm.value.depositoryType;
  if (
    (depositoryType == 1 && !newForm.value.depositoryId) ||
    (depositoryType == 2 &&
      (!newForm.value.depositoryId || !newForm.value.storeId))
  ) {
    searchGoodsList.value = [];
    newForm.value.goodsList = [];
    chooseGoodsVal.value = [];
    message(depositoryType == 2 ? "请选择仓库、门店" : "请选择仓库", {
      type: "warning"
    });
    searchLoading.value = false;
    return;
  }

  const params = {
    transferType: depositoryType == 1 ? 1 : 2,
    storeId: newForm.value.storeId,
    search: searchKey,
    depositoryId: newForm.value.depositoryId,
    pageNum: 1,
    pageSize: 20
  };
  const { data } = await getTransferSearch(params);
  searchGoodsList.value = data || [];

  setTimeout(() => {
    searchLoading.value = false;
  }, 100);
};

const chooseGoodsChange = val => {
  let specCode = val[0];
  let index = chooseGoodsVal.value.indexOf(specCode);
  if (index == -1) {
    chooseGoodsVal.value.push(specCode);
    let goods = searchGoodsList.value.find(v => v.specCode == specCode);
    if (goods && goods.specCode) {
      newForm.value.goodsList.push(goods);
    }
  } else {
    // 移除
    chooseGoodsVal.value.splice(index, 1);
    let findIndex = newForm.value.goodsList.findIndex(
      v => v.specCode == specCode
    );
    if (findIndex != -1) {
      newForm.value.goodsList.splice(findIndex, 1);
    }
  }
};

const handleDelete = (row, index) => {
  newForm.value.goodsList.splice(index, 1);

  // 移除选中的商品id
  let removeIndex = chooseGoodsVal.value.indexOf(row.specCode);
  if (removeIndex != -1) {
    chooseGoodsVal.value.splice(removeIndex, 1);
  }
};

function getForm() {
  return new Promise(resolve => {
    let obj: any = {
      isPass: false,
      params: {}
    };
    ruleFormRef.value.validate(async valid => {
      if (!valid) {
        resolve(obj);
        return;
      }

      if (newForm.value.goodsList.length == 0) {
        resolve(obj);
        return message("调账商品不可为空", { type: "warning" });
      }

      let filterList = newForm.value.goodsList.filter(v => v.actualNum);
      if (filterList.length == 0) {
        resolve(obj);
        return message("商品列表至少填写一个实际库存数量", { type: "warning" });
      }

      obj.params = {
        transferType: newForm.value.depositoryType == 1 ? 1 : 2,
        storeId: newForm.value.storeId,
        depositoryId: newForm.value.depositoryId,
        processNumber: newForm.value.processNumber,
        transferDetailAddRequests: filterList.map(v => {
          v.varianceNum =
            Number(v.actualNum || 0) - Number(v.inventoryNum || 0);
          return v;
        })
      };
      obj.isPass = true;
      resolve(obj);
    });
  });
}

watch(
  () => newForm.value.depositoryId,
  newVal => {
    searchGoodsList.value = [];
    newForm.value.goodsList = [];
    chooseGoodsVal.value = [];
  }
);

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef, getForm });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newForm"
    :rules="formRules"
    label-width="125px"
    class="pd-form"
  >
    <el-form-item label="仓库类型" prop="depositoryType">
      <el-select
        v-model="newForm.depositoryType"
        placeholder="请选择"
        class="!w-[330px]"
        @change="newForm.depositoryId = ''"
      >
        <el-option label="平台仓库" :value="1" />
        <el-option label="门店仓库" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="选择仓库" prop="depositoryId">
      <el-select
        v-model="newForm.depositoryId"
        clearable
        filterable
        placeholder="请选择"
        class="!w-[330px]"
      >
        <el-option
          v-for="item in showCkList"
          :key="item.id"
          :label="item.depositoryName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="newForm.depositoryType == 2"
      label="所属门店："
      prop="storeId"
    >
      <el-select
        v-model="newForm.storeId"
        clearable
        filterable
        class="!w-[330px]"
        placeholder="请选择"
      >
        <el-option
          v-for="item in selectData.storeList"
          :key="item.id"
          :label="item.storeName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="库存调账流程编号" prop="processNumber">
      <el-input
        v-model="newForm.processNumber"
        clearable
        class="!w-[330px]"
        placeholder="请输入"
      />
    </el-form-item>
    <el-form-item label="快速选择商品" prop="">
      <el-select
        multiple
        filterable
        remote
        reserve-keyword
        :disabled="!newForm.depositoryId"
        placeholder="输入商品编码/条码/名称"
        :remote-method="remoteMethod"
        :loading="searchLoading"
        class="!w-[330px]"
        @change="chooseGoodsChange"
      >
        <el-option
          v-for="item in searchGoodsList"
          :key="item.specCode"
          :label="item.goodsName"
          :value="item.specCode"
          class="min-h-[60px]"
        >
          <div class="flex items-center justify-between py-2">
            <div class="flex items-center">
              <ImageViewer
                width="45px"
                height="45px"
                radius="8px"
                :src="item.specImageJson || item.imageJson"
              />
              <div class="ml-1">
                {{
                  item.specName
                    ? item.goodsName + " (" + item.specName + ")"
                    : item.goodsName
                }}
              </div>
            </div>
            <iconifyIconOffline
              v-if="chooseGoodsVal.includes(item.specCode)"
              class="text-blue-500 text-sm ml-2"
              :icon="EpSelect"
            />
          </div>
        </el-option>
      </el-select>
    </el-form-item>
    <pure-table
      row-key="id"
      align-whole="center"
      :header-cell-style="{
        background: 'var(--el-fill-color-light)',
        color: 'var(--el-text-color-primary)'
      }"
      :data="newForm.goodsList"
      :columns="kcpdColumns"
    >
      <template #operation="{ row, index }">
        <div class="flex justify-center">
          <iconifyIconOffline
            class="text-red-500 text-lg cursor-pointer"
            :icon="Delete"
            @click="handleDelete(row, index)"
          />
        </div>
      </template>
    </pure-table>
  </el-form>
</template>

<style scoped lang="scss">
.pd-form {
  margin: 10px 10px 25px;
}
</style>
